package com.dianpingmedia.wifitz.ui;


import android.os.Handler;
import android.os.HandlerThread;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zsc
 * @create 2018/7/12 0012
 * @Describe
 */
public class Test2 {
    private static Handler mHandler;
    private static Gson mGson = new Gson();

    static {
        HandlerThread handlerThread = new HandlerThread("upload");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());
    }


    public static void main(String[] args) {
        //启动上传
        mHandler.post(runnable);
    }


    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //查询数据库前面20条数据
            List<MacBean> macBeans = query(20);
            if (macBeans != null && macBeans.size() > 0) {
                //存在数据上传
                boolean upload = upload(mGson.toJson(macBeans));
                if (upload) {
                    //上传成功
                    delete(macBeans.get(macBeans.size() - 1).id);
                } else {
                    //上传失败,随机延迟1-10秒再次上传,看看是否连通或者看返回的是什么数据，根据服务端返回的错误码做相应的处理
                    mHandler.postDelayed(this, (long) ((Math.random() * 10) + 1) * 1000);
                }
            } else {
                //没有数据延迟1小时再次尝试
                mHandler.postDelayed(this, 60 * 60 * 1000);
            }
        }
    };

    private static void delete(long id) {
        //删除掉已经上传完毕的数据
    }

    private static boolean upload(String json) {
        return true;
    }

    private static List<MacBean> query(int limit) {
        return new ArrayList<MacBean>();
    }

    private class MacBean {
        public String mac;
        public long id;
    }
}
